package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.ApAuthorService;
import com.heima.article.service.FreeMarkerService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-09-15
 */
@Slf4j
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {


    @Autowired
    private ApArticleContentService contentService;
    @Autowired
    private ApAuthorService apAuthorService;
    @Autowired
    private FreeMarkerService freeMarkerService;
    /**
     * 保存文章数据
     * 保存ap_article
     * 保存ap_article_content
     * @param dto
     * @return  文章articleId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveArticle(WmNewsResultDTO dto) {
//        根据自媒体文章id查询article信息
        Integer wmNewsId = dto.getId();
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getWmNewsId,wmNewsId);
        ApArticle article = getOne(queryWrapper);
//        保存/修改 文章表
        if(article==null){
//            新增
            article  = BeanHelper.copyProperties(dto,ApArticle.class);
            article.setId(null);
//            自媒体用户id
            Integer wmUserId = dto.getWmUserId();
//            根据wmUserId，查询文章作者数据
            ApAuthor apAuthor = apAuthorService.getByWmUserId(wmUserId);
            if(apAuthor != null) {
                article.setAuthorId(apAuthor.getId());
                article.setAuthorName(apAuthor.getName());
            }
            article.setLayout(dto.getType());
            article.setFlag(0);
            article.setLikes(0L);
            article.setComments(0L);
            article.setViews(0L);
            article.setCollection(0L);
            article.setCreatedTime(new Date());
            article.setPublishTime(dto.getPublishTime()==null?new Date():dto.getPublishTime());
            article.setIsComment(true);
            article.setIsForward(true);
            article.setIsDelete(false);
            article.setIsDown(false);
            article.setWmNewsId(wmNewsId);
            boolean b = save(article);
            if(!b){
                log.error("新增文章失败，wmNewsId={}",wmNewsId);
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
        }else{
            article.setTitle(dto.getTitle());
            article.setChannelId(dto.getChannelId());
            article.setChannelName(dto.getChannelName());
            article.setLabels(dto.getLabels());
            article.setImages(dto.getImages());
            article.setLayout(dto.getType());
            article.setPublishTime(dto.getPublishTime()==null?new Date():dto.getPublishTime());
//            修改
            boolean b = updateById(article);
            if(!b){
                log.error("修改文章失败，articleId={}",article.getId());
                throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
            }
        }
//        文章id
        Long articleId = article.getId();
//        保存/修改文章内容表
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(articleId);
        apArticleContent.setContent(dto.getContent());
        boolean b = contentService.saveOrUpdate(apArticleContent);
        if(!b){
            log.error("新增/修改文章内容失败，articleId={}",articleId);
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

        log.info("---------发布成功");
//        发布成功后，生成静态页面，存储到minio，保存页面的url
        freeMarkerService.createHtml(articleId,dto.getContent());
//      其他业务
        return articleId;
    }

    /**
     * 文章列表首页
     * 分页
     * @param dto
     * @return
     */
    @Override
    public List<ArticleDto> loadArticle(ArticleHomeDto dto,int type) {

        IPage<ApArticle> ipage = new Page<>(1,dto.getSize());
//        设置条件
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.
                eq(ApArticle::getIsDown,false).
                eq(ApArticle::getIsDelete,false);
        if(dto.getChannelId() !=0){
//            根据频道id查询文章
            queryWrapper.eq(ApArticle::getChannelId,dto.getChannelId());
        }
        if(dto.getMaxTime() != null && type==1){
//            查询更新，比当前列表的最大发布时间还要晚的文章
            queryWrapper.gt(ApArticle::getPublishTime,dto.getMaxTime());
        }
        if(dto.getMinTime() != null && type==2){
//            查询更多，比当前列表的最小发布时间还要早的文章
            queryWrapper.lt(ApArticle::getPublishTime,dto.getMinTime());
        }
//        排序
        queryWrapper.orderByDesc(ApArticle::getPublishTime);
//        分页查询
        IPage<ApArticle> articleIPage = page(ipage, queryWrapper);
        if(CollectionUtils.isEmpty(articleIPage.getRecords())){
            log.error("文章数据不存在");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return BeanHelper.copyWithCollection(articleIPage.getRecords(),ArticleDto.class);
    }

    @Override
    public void downOrUp(Map<String, Long> map) {

        Long articleId = map.get("articleId");
//        1-上架  0-下架
        Long enable = map.get("enable");
        Boolean isDown = (enable==0);

        ApArticle apArticle = new ApArticle();
        apArticle.setId(articleId);
        apArticle.setIsDown(isDown);
        boolean b = updateById(apArticle);

    }
    /**
     * 分页查询 文章列表
     * @param page
     * @param size
     * @return
     */
    @Override
    public List<ArticleDto> findByPage(Integer page, Integer size) {
//        设置分页条件
        IPage<ApArticle> iPage = new Page<>(page,size);
//        分页查询
        List<ArticleDto> list = getBaseMapper().selectArticleAndContentByPage(iPage);
//        返回构造数据
        return list;
    }
}
